import XmindViewer from "./src/index";

/**
 * 加载本地文件
 * @param {File} file 
 * @returns 
 */
async function readFile(file) {
  console.info('Reading file')
  return new Promise((resolve, reject) => {
    var reader = new FileReader()
    reader.onloadend = (e) => {
      console.info('File read.')
      resolve(e.target.result)
    }
    reader.onerror = e => {
      console.error('Load failure', e)
      reject(e)
    }

    reader.readAsArrayBuffer(file)
  })
}

/**
 * 加载远程文件
 * @param {String} url 
 * @returns 
 */
async function loadUrl(url) {
  const response = await fetch(url);
  return response.arrayBuffer();
}

/**
 * 执行渲染
 * @param {ArrayBuffer} data XMind 文件内容
 */
function render(data) {
  const container = document.getElementById("app");
  const header = document.getElementById('header')
  XmindViewer.viewer.render(container, data, null, [header])
}

window.onload = function () {
  loadUrl("./LIST OF POISONING AND TREATMENT DRUGS.xmind").then(data => {
    render(data)
  })

  document.getElementById('file').addEventListener('change', (e) => {
    var file = e.target.files[0]
    if (!file) {
      return
    }
    readFile(file).then(data => {
      render(data)
    })
  })
}